#include "managealert.h"
#include "ui_managealert.h"

ManageAlert::ManageAlert()
{
    setupUi(this);
    setWindowFlags(Qt::WindowTitleHint | Qt::WindowMinimizeButtonHint);
    connect(manageAlertNameID, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(openAlertInfo(QListWidgetItem*)));
    layout()->setSizeConstraint(QLayout::SetFixedSize);
}
void ManageAlert::on_manageAlertAddButton_clicked(){
    addAlert = new AddAlert();
    connect(addAlert, SIGNAL(on_addAlertCancelButton_clicked()), this, SLOT(enableWindow()));
    connect(addAlert, SIGNAL(add(Alert)), this, SLOT(receiveAdd(Alert)));
    connect(addAlert, SIGNAL(on_addAlertAcceptButton_clicked()), this, SLOT(enableWindow()));
    connect(addAlert, SIGNAL(on_addAlertAcceptButton_clicked()), addAlert, SLOT(construct()));
    this->setDisabled(true);
    addAlert->show();
}
void ManageAlert::on_manageAlertCloseButton_clicked(){
    updateAlertList(alertList);
    close();
    this->close();
}

void ManageAlert::enableWindow(){
    this->setDisabled(false);
}
void ManageAlert::openAlertInfo(QListWidgetItem* item){
    alertInfo = new AlertInfo(searchAlerts(item->text().toStdString()));
    connect(alertInfo, SIGNAL(remove(Alert)), this, SLOT(receiveDelete(Alert)));
    connect(alertInfo, SIGNAL(modify(Alert,Alert)), this, SLOT(receiveModify(Alert,Alert)));
    connect(alertInfo, SIGNAL(on_alertCancelButton_clicked()), this, SLOT(enableWindow()));
    connect(alertInfo, SIGNAL(on_alertAcceptButton_clicked()), this, SLOT(enableWindow()));
    connect(alertInfo, SIGNAL(on_alertAcceptButton_clicked()), alertInfo, SLOT(checkEdited()));
    connect(alertInfo, SIGNAL(on_deleteAlertButton_clicked()), alertInfo, SLOT(removeAlert()));
    connect(alertInfo, SIGNAL(on_deleteAlertButton_clicked()), this, SLOT(enableWindow()));
    this->setDisabled(true);
    alertInfo->show();
}
void ManageAlert::receiveAdd(Alert alert){
    alertList.addAlert(alert);
    reloadAlertList();
}
void ManageAlert::receiveDelete(Alert alert){
    alertList.deleteAlert(alert);
    reloadAlertList();
}
void ManageAlert::receiveModify(Alert oldAlert, Alert newAlert){
    newAlert.print();
    alertList.modifyAlert(oldAlert, newAlert);
    reloadAlertList();
}
Alert ManageAlert::searchAlerts(string input){
    int i = 0;
    for(i = 0; i < alertList.size(); i++){
        if(alertList[i].getnameid() == input)
            return alertList[i];
    }
}
void ManageAlert::reloadAlertList(){
    int i = 0;
    manageAlertNameID->clear();
    manageAlertDateTime->clear();

    for(i = 0; i < alertList.size(); i++){
        manageAlertNameID->addItem(QString::fromStdString(alertList[i].getnameid()));
        manageAlertDateTime->addItem(alertList[i].sgetdatetime());
    }
}

void ManageAlert::setAlertList(AlertList alertList){
    this->alertList = alertList;
}
